<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import dayjs from 'dayjs';
import { useDateStore } from '@/store/date';
const dateStore = useDateStore();

const calendarWeekArray = ['一', '二', '三', '四', '五', '六', '日']

const calendarDateArray = ref<string[][]>([])

const getCalendarDates = (baseDate: any): dayjs.Dayjs[] => {
  // 当前日期和月的第一天
  // const now = dayjs()
  const firstDayOfMonth = baseDate.startOf('month')

  // 获取当前月第一天是周几，0 表示周日
  const startDayOfWeek = firstDayOfMonth.day()

  // 前置天数（以周日为起始）
  const prevDays = startDayOfWeek === 0 ? 6 : startDayOfWeek - 1

  // 当前月的天数
  const daysInMonth = baseDate.daysInMonth()

  // 后置天数
  const totalDays = 42 // 日历共 42 天
  const nextDays = totalDays - daysInMonth - prevDays

  // 前一个月的日期
  const prevMonthDates = Array.from({ length: prevDays }, (_, i) =>
    firstDayOfMonth.subtract(prevDays - i, 'day')
  )

  // 当前月的日期
  const currentMonthDates = Array.from({ length: daysInMonth }, (_, i) =>
    firstDayOfMonth.add(i, 'day')
  )

  // 下一个月的日期
  const nextMonthDates = Array.from({ length: nextDays }, (_, i) =>
    firstDayOfMonth.add(daysInMonth + i, 'day')
  )

  // 合并所有日期
  return [...prevMonthDates, ...currentMonthDates, ...nextMonthDates]
}

// 一行显示 7 个日期
const chunkArray = <T>(array: T[], chunkSize: number): T[][] => {
  const result: T[][] = []
  for (let i = 0; i < array.length; i += chunkSize) {
    result.push(array.slice(i, i + chunkSize))
  }
  return result
}

const formatDay = (date: string) => {
  return Number(dayjs(date).format('DD'))
}

const currentCheckedDate = ref<string>('');

const currentDate = ref(dayjs()) // 当前显示的日期

// 当前年
const currentYear = ref<string>('')
// 当前月
const currentMonth = ref<any>('')

const monthMap: Record<number, string> = reactive({
  1: '一月',
  2: '二月',
  3: '三月',
  4: '四月',
  5: '五月',
  6: '六月',
  7: '七月',
  8: '八月',
  9: '九月',
  10: '十月',
  11: '十一月',
  12: '十二月',
})

const emit = defineEmits(['currentDate'])

// 点击选择日期
const handleClickDate = (date: string) => {
  // console.log('🚀 ~ handleClickDate ~ date:', date)
  currentCheckedDate.value = date
}

onMounted(() => {
  fetchDateList()
})

const handleRefresh = () => {
  currentDate.value = dayjs()
  currentCheckedDate.value = dayjs(currentDate.value).format('YYYY-MM-DD')
  fetchDateList()
}

const fetchDateList = () => {
  // 调用函数获取日期数据
  const calendarDates = getCalendarDates(currentDate.value)
  const list = calendarDates.map((date) => date.format('YYYY-MM-DD'))
  calendarDateArray.value = chunkArray(list, 7)
  currentYear.value = dayjs(currentDate.value).format('YYYY')
  currentMonth.value = Number(dayjs(currentDate.value).format('MM'))
}

// 判断日期是不是属于当前月
const handleIsCurrentMonth = (date: string) => {
  const dateMonth = Number(dayjs(date).format('MM'))
  return dateMonth !== currentMonth.value
}

// 切换上一年
const handlePrevYear = () => {
  currentDate.value = dayjs(currentDate.value).subtract(1, 'year')
  fetchDateList()
}

// 切换上一月
const handlePrevMonth = () => {
  currentDate.value = currentDate.value.subtract(1, 'month')
  fetchDateList()
}
// 切换下一月
const handleNextMonth = () => {
  currentDate.value = currentDate.value.add(1, 'month')
  fetchDateList()
}
// 切换下一年
const handleNextYear = () => {
  currentDate.value = currentDate.value.add(1, 'year')
  fetchDateList()
};

watch(
  () => currentCheckedDate.value,
  (date) => {
    emit('currentDate', date)
  }
);

</script>

<template>
  <div class="calendar-container bg-[#fff]">
    <div class="calendar-header py-[0.2rem] flex justify-between">
      <div class="flex items-center text-[0.3rem]" style="white-space: nowrap;">今日待办</div>
      <div class="flex items-center">
        <div class="date-icon-wrap flex items-center">
          <i class="prev-year iconfont icon-a-fanhuibeifen2" @click="handlePrevYear" style="font-size: .36rem;" />
          <i class="iconfont icon-xiangzuo" @click="handlePrevMonth" style="font-size: .36rem;" />
          <div class="px-[0.22rem] mx-[0.04rem] text-[0.3rem]" style="white-space: nowrap;">
            {{ currentYear }} {{ monthMap[currentMonth] }}
          </div>
          <i class="next-month iconfont icon-xiangyou" @click="handleNextMonth" style="font-size: .36rem;" />
          <i class="next-year iconfont icon-fanhuibeifen" @click="handleNextYear" style="font-size: .36rem;" />
        </div>
      </div>
      <div class="flex items-center">
        <i
          class="cursor-pointer iconfont icon-shuaxin text-[#0077FF]"
          style="font-size: .32rem;"
          @click="handleRefresh"
        ></i>
      </div>
    </div>
    <div class="calendar-main">
      <div class="flex flex-col">
        <div class="flex">
          <div
            v-for="(item, index) in calendarWeekArray"
            :key="index"
            class="day-item"
          >
            {{ item }}
          </div>
        </div>
        <div class="flex flex-col">
          <div
            v-for="(item, index) in calendarDateArray"
            :key="index"
            class="flex mb-[0.16rem]"
          >
            <div
              v-for="(it, idx) in item"
              :key="idx"
              class="date-item py-[0.09rem] flex items-center justify-center"
            >
              <div
                class="date cursor-pointer flex items-center justify-center"
                :class="{
                  today: it === dayjs().format('YYYY-MM-DD'),
                  current: currentCheckedDate === it,
                  otherDay: handleIsCurrentMonth(it),
                }"
                @click="handleClickDate(it)"
              >
                {{ formatDay(it) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div>这是测试store</div>
  <div>这是dateStore--{{ dateStore.num }}</div>
  <div>这是getters--- {{ dateStore.doubleDate }}</div>
  <el-button type="primary" @click="dateStore.restore">恢复</el-button>
</template>

<style lang="less" scoped>
.flex { display: flex; }
.flex-col {
    flex-direction: column;
}
.calendar-container {
  background-color: #fff;
  padding: 0 0.2rem;
}

.calendar-header {
  padding: 0.2rem 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.calendar-header .flex.items-center {
  white-space: nowrap;
  font-size: 30px;
}

.calendar-header .date-icon-wrap {
  display: flex;
  align-items: center;
}

.calendar-header .date-icon-wrap i {
  font-size: 0.36rem;
  color: rgba(0, 0, 0, 0.25);
  cursor: pointer;
}

.calendar-header .date-icon-wrap .prev-year {
  transform: rotate(90deg);
}

.calendar-header .date-icon-wrap .next-year {
  transform: rotate(90deg);
}

.calendar-header .date-icon-wrap  {
  white-space: nowrap;
  font-size: 20px;
}

.calendar-header .flex.items-center .iconfont.icon-shuaxin {
  cursor: pointer;
  font-size: 32px;
  color: #0077FF;
}

.calendar-main {
  padding: 20px 0;
  display: flex;
  flex-direction: column;
}

.calendar-main .day-item {
  flex: 1;
  font-size: 0.31rem;
  text-align: center;
  padding: 0.31rem 0;
}

.calendar-main .date-item {
  font-size: 0.31rem;
  color: rgba(0, 0, 0, 0.85);
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.calendar-main .date {
  width: 0.53rem;
  height: 0.53rem;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
}

.calendar-main .date.today {
  background-color: #0077ff;
  color: #fff;
}

.calendar-main .date.current {
  border: 0.02rem solid #0077ff;
  color: #0077ff;
}

.calendar-main .date.otherDay {
  color: rgba(0, 0, 0, 0.25);
}
</style>